package com.hmdp.utils;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicLong;

public class RedisSnowflakeIdUtil {
    private static Logger logger = LoggerFactory.getLogger(SnowflakeIdUtil.class.getName());

    /** 时间戳调整为秒级（32位，可表示约136年）*/
    private static final long twepoch = 1727712000L;  // 2024-10-01 00:00:00（秒级时间戳）

    /** 调整后的位数分配 */
    private static final int WORKER_ID_BITS = 10;    // 机器ID（10位，1024节点）
    private static final int SEQUENCE_BITS = 11;     // 序列号（11位，每秒2048个）

    /** 位移数调整 */
    private static final int WORKER_ID_SHIFT = SEQUENCE_BITS;
    private static final int TIMESTAMP_SHIFT = WORKER_ID_BITS + SEQUENCE_BITS;

    /** 最大值 */
    private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1;
    private static final long MAX_SEQUENCE = (1L << SEQUENCE_BITS) - 1;

    private long sequence = 0L;
    private int workerId;
    private long lastTimestamp = -1L;
    private volatile static RedisSnowflakeIdUtil instance = null;

    // 修改构造函数
    private RedisSnowflakeIdUtil() {
        workerId = getWorkId();
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("workerId must be between 0 and 1023");
        }
    }

    public static RedisSnowflakeIdUtil getInstance() {
        if (instance == null) {
            synchronized (RedisSnowflakeIdUtil.class) {
                if (instance == null) {
                    instance = new RedisSnowflakeIdUtil();
                }
            }
        }
        return instance;
    }

    // 保持原有getWorkId逻辑不变
    private int getWorkId() {
        try {
            String hostAddress = SystemInfo.getHostAddress();
            int[] ints = StringUtils.toCodePoints(hostAddress);
            int sums = 0;
            for (int b : ints) {
                sums = sums + b;
            }
            return (sums % 1024);
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
            return RandomUtils.nextInt(0, 1024);
        }
    }

    public synchronized long nextId() {
        long now = getTimestamp();  // 现在获取秒级时间戳

        // 处理时钟回拨（调整为秒级回拨）
        if (now < lastTimestamp) {
            long offset = lastTimestamp - now;
            if (offset <= 1) {  // 允许最多1秒的回拨补偿
                try {
                    Thread.sleep(1000 * (offset + 1));
                    now = getTimestamp();
                    if (now < lastTimestamp) {
                        throw new RuntimeException("时钟回拨无法恢复");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                throw new RuntimeException(String.format("时钟回拨过大 %d 秒", offset));
            }
        }

        if (lastTimestamp == now) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                now = waitNextSecond(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = now;

        // 新的ID生成逻辑（总位数53位）
        long id = ((now - twepoch) << TIMESTAMP_SHIFT)
                | ((long) workerId << WORKER_ID_SHIFT)
                | sequence;

        // 安全验证（开发阶段启用）
        // if (id > 9007199254740991L) throw new RuntimeException("ID超过安全范围");

        return id;
    }

    // 改为获取秒级时间戳
    protected long getTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    // 等待下一秒
    private long waitNextSecond(long lastTimestamp) {
        long now;
        do {
            now = System.currentTimeMillis() / 1000;
        } while (now <= lastTimestamp);
        return now;
    }
}